package setting

import (
	"encoding/json"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core/response"
	"likeadmin/util"
)

type ISettingLoginService interface {
	Detail() (res resp.SettingLoginResp, e error)
	Save(editReq req.SettingLoginReq) (e error)
}

// NewSettingLoginService 初始化
func NewSettingLoginService(db *gorm.DB) ISettingLoginService {
	return &settingLoginService{db: db}
}

// settingLoginService 系统登录服务实现类
type settingLoginService struct {
	db *gorm.DB
}

// 配置详情
func (loginSrv settingLoginService) Detail() (res resp.SettingLoginResp, e error) {
	str, err := util.ConfigUtil.GetVal(loginSrv.db, "login", "config", "{\"loginWay\":[1,2],\"forceBindMobile\":0,\"openAgreement\":1,\"openOtherAuth\":1,\"autoLoginAuth\":[1,2]}")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}
	_ = json.Unmarshal([]byte(str), &res)
	return
}

// Save
func (loginSrv settingLoginService) Save(editReq req.SettingLoginReq) (e error) {
	marshal, err := json.Marshal(editReq)
	if err != nil {
		if e = response.CheckErr(err, "Save Set name err"); e != nil {
			return
		}
	}
	err = util.ConfigUtil.Set(loginSrv.db, "login", "config", string(marshal))
	if e = response.CheckErr(err, "Save Set name err"); e != nil {
		return
	}

	// 更新缓存
	util.RedisUtil.HDel("login", "config")

	return
}
